/**
    Copyright (C) 2011  Alexander Vollmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jefb.web.controller;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.jefb.entity.CommonSearchCriteria;
import org.jefb.entity.IBasicEntity;
import org.jefb.service.ICommonPersistenceService;
import org.jefb.web.model.EntityModel;
import org.jefb.web.model.MessagesModel;
import org.jefb.web.model.entity.Message;
import org.jefb.web.model.entity.MessageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.zkoss.lang.Strings;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listhead;
import org.zkoss.zul.Listheader;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Panel;
import org.zkoss.zul.event.PagingEvent;

@SuppressWarnings("serial")
public abstract class EntityController<T extends IBasicEntity> extends GenericForwardComposer implements Serializable{

	//Services
	@Autowired
	private ICommonPersistenceService commonPersistenceService;
	
	// auto-wired ZK components
	protected Listbox entityList;
	protected Paging listPaging;
	
	//destination management panels
	protected Panel addPanel;
	protected Panel editPanel;
	
	protected abstract String[] getColumnIds();
	protected abstract T createNewEntityInstance();
	
	//models
//	@Autowired
//	private EntityModel<T> entityModel;
	@Autowired
	private MessagesModel messagesModel;
	
	public abstract EntityModel<T> getModel();

//	public void setModel(EntityModel<T> newModel) {
//		this.entityModel = newModel;
//	}
	
	private CommonSearchCriteria commonSearchCriteria = new CommonSearchCriteria();

	public EntityController() {
	}
	
	/**
	 * Init method. Will be called by Spring.
	 */
	@PostConstruct
	public void init() {
		//resetModel();
		getModel().setNewEntity(createNewEntityInstance());
		getModel().setSearchCriteria(createNewEntityInstance());
		List<?> findByCriteria = this.commonPersistenceService.findByCriteria(
					getModel().getSearchCriteria(), commonSearchCriteria);
		getModel().setListModel(new BindingListModelList(findByCriteria, false));
	}
	
	/* (non-Javadoc)
	 * @see org.zkoss.zk.ui.util.GenericComposer#doBeforeComposeChildren(org.zkoss.zk.ui.Component)
	 */
	@Override
	public void doBeforeComposeChildren(Component comp) throws Exception {
		super.doBeforeComposeChildren(comp);
		getModel().resetModel();
	}
	
	protected boolean addModeEnabled = false;
	
	protected void setAddMode(){
		resetModel();
		addPanel.setVisible(true);
		editPanel.setVisible(false);
		entityList.clearSelection();
		getModel().setNewEntity(createNewEntityInstance());
		addModeEnabled = true;
	}
	
	protected void setEditMode(){
		addPanel.setVisible(false);
		editPanel.setVisible(true);
		addModeEnabled = false;
	}

	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		reloadList();
		listPaging.setPageSize(commonSearchCriteria.getPageSize());
		listPaging.setTotalSize(commonPersistenceService
				.getTotalSizeByCriteria(getModel().getSearchCriteria()).intValue());
		listPaging.addEventListener("onPaging", new EventListener() {
			public void onEvent(Event event) throws Exception {
				PagingEvent pe = (PagingEvent) event;
				int pageNo = pe.getActivePage();
				commonSearchCriteria.setPagingStart(pageNo
						* commonSearchCriteria.getPageSize());
				reloadList();
			}
		});

		Listhead listhead = entityList.getListhead();
		List<?> list = listhead.getChildren();

		for (int i = 0; i < list.size(); i++) {
			Object object = list.get(i);
			if (object instanceof Listheader) {
				final Listheader lheader = (Listheader) object;
				lheader.setAttribute("columnId", getColumnIds()[i]);
				if (lheader.getSortAscending() != null
						|| lheader.getSortDescending() != null) {
					lheader.addEventListener("onSort", new EventListener() {
						public void onEvent(Event event) throws Exception {
							final Listheader lh = (Listheader) event
									.getTarget();
							final String sortDirection = lh.getSortDirection();
							if ("ascending".equals(sortDirection)) {
								commonSearchCriteria.setSortField(lheader
										.getAttribute("columnId").toString());
								commonSearchCriteria.setSortDirection("DESC");
								reloadList();
							} else if ("descending".equals(sortDirection)
									|| "natural".equals(sortDirection)
									|| Strings.isBlank(sortDirection)) {
								commonSearchCriteria.setSortField(lheader
										.getAttribute("columnId").toString());
								commonSearchCriteria.setSortDirection("ASC");
								reloadList();
							}
						}
					});
				}
			}
		}
	}
	
	@SuppressWarnings("rawtypes")
	private void reloadList() {
		List findByCriteria = this.commonPersistenceService.findByCriteria(
				getModel().getSearchCriteria(), commonSearchCriteria);
		getModel().getListModel().clear();
		getModel().getListModel().addAll(findByCriteria);
		Integer totalSize = commonPersistenceService
				.getTotalSizeByCriteria(getModel().getSearchCriteria()).intValue();
		listPaging.setTotalSize(totalSize);
	}
	
	public void onClick$cancelAddButton(Event event){
		resetModel();
	}

	public void onClick$showAddPanelButton(Event event){
		setAddMode();
	}
	

	public void onClick$addButton(Event e) {
		getModel().getNewEntity().setCreationTime(new Date());
		getModel().getNewEntity().setLastUpdateTime(new Date());
		this.commonPersistenceService.persistEntity(getModel().getNewEntity());
		resetModel();
		reloadList();
		messagesModel.addMessage(new Message("common.msg.data_saved",
				MessageType.SUCCESS));
		//ZKUtils.showInfo("common.msg.data_saved");
	}

	public void onSelect$entityList(Event e) {
		setEditMode();
	}

	public void onClick$deleteButton(Event e) {
		if(getModel().getSelectedEntity()!=null){
			commonPersistenceService.deleteEntity(getModel().getSelectedEntity());
			resetModel();
			reloadList();
		}
	}

	public void onClick$updateButton(Event e) {
		T selectedEntity = getModel().getSelectedEntity();
		if (selectedEntity != null) {
			selectedEntity.setLastUpdateTime(new Date());
			this.commonPersistenceService.updateEntity(selectedEntity);
			resetModel();
			reloadList();
			messagesModel.addMessage(new Message("common.msg.data_saved",
					MessageType.SUCCESS));
			//ZKUtils.showInfo("common.msg.data_saved");
		}
	}

	public ICommonPersistenceService getCommonPersistenceService() {
		return commonPersistenceService;
	}

	public void setCommonPersistenceService(
			ICommonPersistenceService commonPersistenceService) {
		this.commonPersistenceService = commonPersistenceService;
	}
	
	/**
	 * Reset entity model.
	 */
	protected void resetModel(){
		getModel().resetModel();
		hidePanels();
	}
	
	private void hidePanels(){
		if(addPanel!=null){
			addPanel.setVisible(false);
		}
		if(editPanel!=null){
			editPanel.setVisible(false);
		}
	}
	
	public void setMessagesModel(MessagesModel messagesModel) {
		this.messagesModel = messagesModel;
	}
	public MessagesModel getMessagesModel() {
		return messagesModel;
	}

}
